<?php

// PHP雪里开轻量级报修系统 V1.0Beta
// 演示地址: http://baoxiu.chalide.cn
// 更新关注: /weivote
// 文件路径: inc/sqls.php
// 文件大小: 5878 字节
// 最后修改时间: 2025-05-21 14:49:04
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权

/**
 * 本文件功能：数据库操作类
 * 版权声明：保留发行权和署名权
 * 作者信息：功能反馈:15058593138@qq.com(手机号同微信)
 */

class Database {
    private $mysqli;
    private $prefix;
    
    // 构造函数
    public function __construct($mysqli) {
        $this->mysqli = $mysqli;
        $this->prefix = defined('DB_PREFIX') ? DB_PREFIX : '';
    }
    
    // 获取表名（带前缀）
    private function getTable($table) {
        return $this->prefix . $table;
    }
    
    // 查询单条记录
    public function getOne($table, $condition = '1=1', $fields = '*') {
        $table = $this->getTable($table);
        $sql = "SELECT {$fields} FROM {$table} WHERE {$condition} LIMIT 1";
        $result = $this->mysqli->query($sql);
        
        if ($result && $result->num_rows > 0) {
            return $result->fetch_assoc();
        }
        
        return null;
    }
    
    // 查询多条记录
    public function getAll($table, $condition = '1=1', $fields = '*', $order = '', $limit = '') {
        $table = $this->getTable($table);
        $sql = "SELECT {$fields} FROM {$table} WHERE {$condition}";
        
        if (!empty($order)) {
            $sql .= " ORDER BY {$order}";
        }
        
        if (!empty($limit)) {
            $sql .= " LIMIT {$limit}";
        }
        
        $result = $this->mysqli->query($sql);
        $data = [];
        
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        
        return $data;
    }
    
    // 分页查询
    public function pager($table, $condition = '1=1', $fields = '*', $order = '', $page = 1, $page_size = 10) {
        $table = $this->getTable($table);
        
        // 计算总记录数
        $count_sql = "SELECT COUNT(*) as total FROM {$table} WHERE {$condition}";
        $count_result = $this->mysqli->query($count_sql);
        $total = 0;
        
        if ($count_result && $count_result->num_rows > 0) {
            $count_row = $count_result->fetch_assoc();
            $total = $count_row['total'];
        }
        
        // 计算分页参数
        $page = max(1, intval($page));
        $total_pages = ceil($total / $page_size);
        $offset = ($page - 1) * $page_size;
        
        // 查询数据
        $data = [];
        if ($total > 0) {
            $sql = "SELECT {$fields} FROM {$table} WHERE {$condition}";
            
            if (!empty($order)) {
                $sql .= " ORDER BY {$order}";
            }
            
            $sql .= " LIMIT {$offset}, {$page_size}";
            $result = $this->mysqli->query($sql);
            
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $data[] = $row;
                }
            }
        }
        
        return [
            'data' => $data,
            'page' => $page,
            'page_size' => $page_size,
            'total' => $total,
            'total_pages' => $total_pages
        ];
    }
    
    // 插入记录
    public function insert($table, $data) {
        $table = $this->getTable($table);
        $fields = [];
        $values = [];
        
        foreach ($data as $field => $value) {
            $fields[] = "`{$field}`";
            
            if ($value === null) {
                $values[] = "NULL";
            } else {
                $values[] = "'" . $this->mysqli->real_escape_string($value) . "'";
            }
        }
        
        $fields_str = implode(', ', $fields);
        $values_str = implode(', ', $values);
        
        $sql = "INSERT INTO {$table} ({$fields_str}) VALUES ({$values_str})";
        $result = $this->mysqli->query($sql);
        
        if ($result) {
            return $this->mysqli->insert_id;
        }
        
        return false;
    }
    
    // 更新记录
    public function update($table, $data, $condition) {
        $table = $this->getTable($table);
        $set = [];
        
        foreach ($data as $field => $value) {
            if ($value === null) {
                $set[] = "`{$field}` = NULL";
            } else {
                $set[] = "`{$field}` = '" . $this->mysqli->real_escape_string($value) . "'";
            }
        }
        
        $set_str = implode(', ', $set);
        
        $sql = "UPDATE {$table} SET {$set_str} WHERE {$condition}";
        $result = $this->mysqli->query($sql);
        
        if ($result) {
            return $this->mysqli->affected_rows;
        }
        
        return false;
    }
    
    // 删除记录
    public function delete($table, $condition) {
        $table = $this->getTable($table);
        $sql = "DELETE FROM {$table} WHERE {$condition}";
        $result = $this->mysqli->query($sql);
        
        if ($result) {
            return $this->mysqli->affected_rows;
        }
        
        return false;
    }
    
    // 执行自定义SQL
    public function query($sql) {
        $result = $this->mysqli->query($sql);
        
        if (is_object($result)) {
            $data = [];
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            return $data;
        }
        
        return $result;
    }
    
    // 获取错误信息
    public function getError() {
        return $this->mysqli->error;
    }
    
    // 开始事务
    public function beginTransaction() {
        $this->mysqli->autocommit(false);
    }
    
    // 提交事务
    public function commit() {
        $this->mysqli->commit();
        $this->mysqli->autocommit(true);
    }
    
    // 回滚事务
    public function rollback() {
        $this->mysqli->rollback();
        $this->mysqli->autocommit(true);
    }
}
